package com.schedualnew.mq.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.ctc.wstx.util.StringUtil;
import org.dom4j.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

public class DocUtil {
    private static Logger log = LoggerFactory.getLogger(DocUtil.class);


    public static String fileTostring(String path) {
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path), "GB2312"));
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            in.close();
        } catch (Exception e) {

            e.printStackTrace();
            buffer.append("");
        }
        return buffer.toString();
    }


    public static String editItemText(String reportContent, String itemName, String itemText) {
        String s = reportContent;
        String[] array = reportContent.split("<N>" + itemName + "</N>");
        if (array.length < 2) {
            array = reportContent.split("<N>" + itemName.toUpperCase() + "</N>");
        }
        if (array.length == 2) {
            int end = array[1].indexOf("<T>");
            String str1 = array[1].substring(0, end + 3);

            int begin = array[1].indexOf("</T>");
            String str2 = array[1].substring(begin);

            s = array[0] + "<N>" + itemName + "</N>" + str1 + itemText + str2;
        } else if (array.length > 2) {

        }


        return s;
    }

    public static String getReportDocXml(String reportContent, Map<String, String> map) {
        String reportDocXml = reportContent;
        if (map != null) {
            Set<String> keySet = map.keySet();
            for (String key : keySet) {
                String descStr = map.get(key);
                if (descStr == null) {
                    descStr = "";
                }
                String srcStr = "#" + key.toLowerCase() + "#";
                reportDocXml = reportDocXml.replace(srcStr, descStr);
            }
        }

        return reportDocXml;
    }


    public static JSONObject xml2Json(String xmlStr) {
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xmlStr);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        JSONObject json = new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }


    public static void dom4j2Json(Element element, JSONObject json) {
        for (Object o : element.attributes()) {
            Attribute attr = (Attribute) o;
            if (StringUtils.hasText(attr.getValue())) {
                json.put("@" + attr.getName(), attr.getValue());
            }
        }
        List<Element> chdEl = element.elements();
        if (!CollectionUtils.isEmpty(chdEl) && StringUtils.hasText(element.getText())) {
            json.put(element.getName(), element.getText());
        }

        for (Element e : chdEl) {
            if (!e.elements().isEmpty()) {
                JSONObject chdjson = new JSONObject();
                dom4j2Json(e, chdjson);
                Object o = json.get(e.getName());
                if (o != null) {
                    JSONArray jsona = null;
                    if (o instanceof JSONObject) {
                        JSONObject jsono = (JSONObject) o;
                        json.remove(e.getName());
                        jsona = new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if (o instanceof JSONArray) {
                        jsona = (JSONArray) o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                    continue;
                }
                if (!chdjson.isEmpty()) {
                    json.put(e.getName(), chdjson);
                }

                continue;
            }
            for (Object o : element.attributes()) {
                Attribute attr = (Attribute) o;
                if (StringUtils.hasText(attr.getValue())) {
                    json.put("@" + attr.getName(), attr.getValue());
                }
            }
            if (!e.getText().isEmpty()) {
                json.put(e.getName(), e.getText());
            }
        }
    }


    public static String convertToXml(Object obj) {
        StringWriter sw = new StringWriter();
        try {
            JAXBContext context = JAXBContext.newInstance(new Class[]{obj.getClass()});
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);

            marshaller.marshal(obj, sw);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return sw.toString().replace("standalone=\"yes\"", "");
    }


    public static Object xmlStrToObject(Class clazz, String xmlStr) {
        Object xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(new Class[]{clazz});

            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);
            xmlObject = unmarshaller.unmarshal(sr);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlObject;
    }
}
